from apps.a_common.log import MyLogger
from apps.foundation import redis

logger = MyLogger('lock')


class lock_by_key:
	def __init__(self, key, timeout=60, blocking=True, blocking_timeout=5):
		"""
		:param timeout:如果 timeout秒 后程序都没结束完，则释放锁
		:param blocking:如果第二个冲突的程序尝试运行，true 等待，false 报错
		:param blocking_timeout:如果blocking is True，那么等待多少秒。超过等待时间会报错
		:return:

		with lock_by_key(key) as pass_:
			if not pass_:
				return
			...
		"""
		logger.info(f'key: {key}, timeout: {timeout}, blocking: {blocking}, blocking_timeout: {blocking_timeout}')
		self.lock = redis.lock(str(key), timeout=timeout, blocking_timeout=blocking_timeout)
		self.timeout = timeout
		self.blocking = blocking
		self.blocking_timeout = blocking_timeout

	def __enter__(self):
		if self.lock.acquire(blocking=self.blocking):  # 如果已有这个key，返回False
			return True
		return False

	def __exit__(self, exc_type, exc_value, exc_trackback):
		self.lock.release()
